var express = require('express')
var router = express.Router()
var connection = require('../db/sql.js')
let user = require('../db/userSql.js')
let jwt = require('jsonwebtoken')

/* GET goods listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a goods')
})

//查询购物车数据
router.post('/selectCart', handlerSelectCart).get('/selectCart', handlerSelectCart)
//修改购物车商品数据
router
  .post('/updateCartGoodsNum', handlerUpdateCartGoodsNum)
  .get('/updateCartGoodsNum', handlerUpdateCartGoodsNum)
//

function getUserByAccount(account) {
  let userInfo = {}
  connection.query(
    'SELECT * FROM vm_user WHERE user_account = ?',
    [account],
    function (error, result) {},
  )
  return userInfo
}
function handlerSelectCart(req, res, next) {
  //token校验
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  console.log('req.headers :>> ', req.headers)

  const account = tokenObj.account || req.body.userAccount || req.query.userAccount
  if (!account) {
    res.send({
      code: 308,
      message: 'token校验失败,建议重新登陆',
    })
  }

  connection.query(
    'SELECT * FROM vm_user WHERE user_account = ?',
    [account],
    function (error, result) {
      let userInfo = result[0] || {}
      if (userInfo?.token === token) {
        connection.query(
          'SELECT uid,goods_id as goodsId,goods_name as goodsName,goods_price as goodsPrice,goods_num as goodsNum,goods_img_url as goodsImgUrl FROM vm_goods_cart WHERE uid = ' +
            userInfo.uid,
          function (err, response) {
            return res.send({
              code: 200,
              data: response,
              message: 'OK',
            })
          },
        )
      } else {
        res.send({
          code: 305,
          message: 'token校验失败,建议重新登陆',
        })
      }
    },
  )
}

function handlerUpdateCartGoodsNum(req, res, next) {
  console.log('/handlerUpdateCartGoodsNum :>> ')
  const goodsId = req.body.goodsId || req.query.goodsId
  const goodsNum = req.body.goodsNum || req.query.goodsNum
  if (!goodsId || !goodsNum) {
    console.log('goodsId,goodsNum :>> ', goodsId, goodsNum)
    return res.send({
      code: 301,
      message: '参数错误',
    })
  }
  console.log(
    'sql :>> ',
    `UPDATE vm_goods_cart SET goods_num = ${goodsNum} WHERE goods_id = ${goodsId}`,
  )
  connection.query(
    'UPDATE vm_goods_cart SET goods_num = ? WHERE goods_id = ?',
    [goodsNum, goodsId],
    function (error, result) {
      if (error) {
        console.error('Database query error:', error)
        return result.status(500).send({
          code: 0,
          message: '服务器内部错误',
        })
      }
      if (result?.affectedRows === 1) {
        res.json({
          code: 200,
          data: result,
          message: '修改成功',
        })
      } else {
        res.json({
          code: 301,
          data: result,
          message: '修改失败',
        })
      }
    },
  )
}

module.exports = router
